package com.arvin.skin.core;

import android.app.Activity;
import android.app.Application;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.view.LayoutInflaterCompat;
import android.view.LayoutInflater;

import com.arvin.skin.core.utils.ClassUtil;
import com.arvin.skin.core.utils.SkinThemeUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import javax.xml.datatype.DatatypeFactory;

public class SkinActivityLifecycle implements Application.ActivityLifecycleCallbacks {
    Map<Activity,SkinLayoutFactory> mLayoutFactoryMap = new HashMap<>();
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        SkinThemeUtils.updateStatusBar(activity);
        LayoutInflater layoutInflater = LayoutInflater.from(activity);
        try {
            Field field = ClassUtil.getField(layoutInflater.getClass(),"mFactorySet");
            field.setAccessible(true);
            field.setBoolean(layoutInflater,false);   /**setFactory 会抛异常*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        SkinLayoutFactory skinLayoutFactory = new SkinLayoutFactory(activity);
        LayoutInflaterCompat.setFactory2(layoutInflater,skinLayoutFactory);
        mLayoutFactoryMap.put(activity,skinLayoutFactory);
        SkinManager.getInstance().addObserver(skinLayoutFactory);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        SkinLayoutFactory remove = mLayoutFactoryMap.remove(activity);
        SkinManager.getInstance().deleteObserver(remove);
    }

    public void updateSkin(Activity activity) {
        mLayoutFactoryMap.get(activity).update(null,null);
    }
}
